import re

from django.contrib.auth.backends import ModelBackend

from users.models import User


def jwt_response_payload_handler(token, user=None, request=None):
    """
    自定义jwt认证成功返回数据
    """
    return {
        'token': token,
        'user_id': user.id,
        'username': user.username
    }


def get_user_by_account(account):
    try:
        if re.match(r'1[3-9]\d{9}', account):
            # 手机号码登陆
            user = User.objects.get(mobile=account)
        else:
            user = User.objects.get(username=account)
    except User.DoesNotExist:
        user = None

    return user


# 重写校验用户登陆方法
class CustomUserLoginAuth(ModelBackend):
    def authenticate(self, request, username=None, password=None, **kwargs):
        """
        实现用户登陆校验

        """
        # 获取用户给
        user = get_user_by_account(username)

        # 用户存在,并且密码正确
        if user and user.check_password(password):
            return user

        return None
